import { observable, computed } from 'mobx';
import { Promise } from 'drunk-base';
import { IEventModel } from './EventModel';
import { getTopic, createTopic, updateTopic } from './TopicHttpResource';
import { getEventOptionsByName } from './EventHttpResource';
import { notEmpty } from '../../../service/Validator';
import { ItemModel, IItemProps, Validate } from '../../ItemModel';

export interface IEvent {
    id: string;
    name: string;
}

export interface ITopicModel extends IItemProps {
    name: string;
    title: string; // 标题
    coverImageUrl: string; // 封面图
    desc: string; // 专题简介
    events: IEvent[]; // 专题里的活动id
}

export class TopicModel extends ItemModel<ITopicModel> {

    private timerId: number;

    @observable data: ITopicModel = {
        name: "",
        title: "", // 标题
        coverImageUrl: "", // 封面图
        desc: "", // 专题简介
        events: [{ name: "", id: "" }], // 专题里的活动id
    };

    @observable eventOptions: IEvent[] = [];

    @Validate(`请输入专题名称`)
    @computed get nameValid() { return notEmpty(this.data.name) }

    @Validate(`请上传一张专题封面图片`)
    @computed get coverImageUrlValid() { return notEmpty(this.data.coverImageUrl) }

    @Validate(`请完善专题简介`)
    @computed get descValid() { return notEmpty(this.data.desc) }

    @Validate(`请选择最少4个活动`)
    @computed get eventsValid() { return this.data.events.length >= 4 && this.data.events.every(event => notEmpty(event.id)) }

    fetchItemImpl(id: string) {
        return getTopic(id);
    }

    createItemImpl(data: ITopicModel) {
        return createTopic(data);
    }

    updateItemImpl(id: string, data: ITopicModel) {
        return updateTopic(id, data);
    }

    addEventAt(position: number) {
        this.data.events.splice(position, 0, { name: "", id: "" });
    }

    deleteEventAt(position: number) {
        this.data.events.splice(position, 1);
    }

    fetchEventOptions(name: string) {
        clearTimeout(this.timerId);

        this.timerId = setTimeout(() => {
            getEventOptionsByName(name).then(res => {
                this.eventOptions = res;
            });
        }, 300);
    }

    updateEventOptions(index: number, id: string) {
        let [options] = this.eventOptions.filter(options => id === options.id);
        this.data.events[index].id = options.id;
        this.data.events[index].name = options.name;
    }
}